package com.dzx.permissionmanagersystem.common;

import com.dzx.permissionmanagersystem.util.JsonMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月29日 12:40:02
 */
@Slf4j
public class HttpInterceptor extends HandlerInterceptorAdapter {
    /**
     * 请求 处理 之前 调用
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String url =request.getRequestURL().toString();

        Map<String,String[]> map  = request.getParameterMap();

        log.info("request 【start】 url:{},params :{}",url, JsonMapper.obj2String(map));
        return true;

    }

    /**
     * 请求成功会调用,如果报异常就不会被调用
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url =request.getRequestURL().toString();

        Map<String,String[]> map  = request.getParameterMap();

        log.info("request 【finish】 url:{},params :{}",url, JsonMapper.obj2String(map));

        removeThreadLocalInfo();
     }

    /**
     * 请求完成就会调用，不管有没有报异常都会被调用
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

        String url =request.getRequestURL().toString();

        Map<String,String[]> map  = request.getParameterMap();

        log.info("request 【complete】 url:{},params :{}",url, JsonMapper.obj2String(map));

       removeThreadLocalInfo();

    }


    public   void  removeThreadLocalInfo(){
        RequestHolder.removeUser();
        RequestHolder.removeRequest();
    }

}
